<?php
function docache($pages){
    $cache_file = "cache/$pages.cache";
    $file = "http://bz.api.xiaolin.in/text?page=" . $pages;
    if(file_exists($cache_file)) {
        if(time() - filemtime($cache_file) > 1728000) {
            // too old , re-fetch
            $html = file_get_contents($file);
            file_put_contents($cache_file, $html);
        }
    } else {
        // no cache, create one
        $html = file_get_contents($file);
        file_put_contents($cache_file, $html);
    }
}


function getbztext($lines,$rand=true,$lang="json"){
    if ($lines<=6){
        $page=1;
    } else {
        $page = floor($lines/6) + 1;
    }
    $line=0;
    for ($a=1;$a<=$page;$a++){
        docache($a);
        $html = file_get_contents("cache/$a.cache");
        if (preg_match_all("/<a href=\"\/articles\/([0-9]+)\" target=\"_blank\">([\s\S]*)<\/a>/U", $html, $matches1)){
            for ($i=0;$i<=6;$i++){
                $result[$line]=$matches1[2][$i];
                $line++;
            }
        }
        if (preg_match_all("/<a href=\"\/articles\/([0-9]+)\?zg_event\=\%E8\%BF\%9B\%E5\%85\%A5\%E5\%8D\%95\%E7\%AF\%87\%E9\%A1\%B5\" data-full-url=\"http:\/\/baozoumanhua.com\/articles\/([0-9]+)\">([\s\S]*)<\/a>/U", $html, $matches2)){
            for ($i=0;$i<=6;$i++){
                $result[$line]=$matches2[3][$i];
                $line++;
            }
        }
    }
    $newr = array_slice($result, 0, $lines);
    if ($rand){
        shuffle($newr);
    }
    /**
    foreach ($newr as $key){
        echo $num . $key . "<br>";
        $num++;
    }
     **/
    if ($lang == "json"){
        $newr[]=$newr[0];
        unset($newr[0]);
        $order   = array("\r\n", "\n", "\r");
        $replace = '&nbsp;&nbsp;';
        $a1 = json_encode($newr,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
        return $a1;
    } elseif ($lang == "text"){
        return $newr;
    } else {
        $newr[]=$newr[0];
        unset($newr[0]);
        $order   = array("\r\n", "\n", "\r");
        $replace = '&nbsp;&nbsp;';
        $a1 = json_encode($newr,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
        return $a1;
    }

}
$rand=true;
if(isset($_GET['rand'])){
    if ($_GET['rand']==0) {
        $rand = false;
    }
}

if(isset($_GET['lang'])){
    $lang = $_GET['lang'];
} else {
    $lang = "json";
}

$check = getbztext($_GET['lines'],$rand,$lang);
if (is_array($check)){
    print_r($check);
} else {
    echo $check;
}
?>
